// 58543
import indexConfig from "@/common/config.js";
// 初始化视频
function initCharts(dataObj, ele) {
  var option = {
    grid: {
      left: "20",
      top: "50",
      right: "20",
      bottom: "50",
    },
    xAxis: [
      {
        type: "category",
        boundaryGap: false,
        axisTick: {
          show: false,
        },
        axisLine: {
          onZero: false,
          lineStyle: {
            color: "#e0e0e0",
            width: 3,
            type: "solid",
          },
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: "#ddd",
          },
        },
        splitLine: {
          show: true,
          lineStyle: {
            // 使用深浅的间隔色
            color: "#e0e0e0",
          },
        },
        data: dataObj.chart.x,
      },
    ],
    yAxis: [
      {
        type: "value",
        axisTick: {
          show: false,
        },
        axisLine: {
          show: false,
        },
        axisLabel: {
          show: false,
        },
        splitLine: {
          lineStyle: {
            color: "#e0e0e0",
          },
        },
      },
    ],
    series: [
      {
        name: "次数",
        type: "line",
        data: dataObj.chart.y,
        symbol:
          "image://http://blue-pi-upload.tianqi.cn/asserts/qdhzy/jc_wd1@2x.png",
        symbolSize: 10,
        smooth: true,
        itemStyle: {
          normal: {
            color: "#0059aa",
            lineStyle: {
              color: "#e74b00",
              width: 3,
            },
            label: {
              show: true,
              formatter: function (value) {
                return "{value|" + value.data + "}";
              },
              rich: {
                value: {
                  color: "#fff",
                  backgroundColor: {
                    image: "./imgs/jc_wd@2x.png",
                  },
                  height: 40,
                  width: 40,
                  lineHeight: 30,
                  align: "center",
                },
              },
            },
          },
        },
      },
    ],
  };
  // 基于准备好的dom，初始化echarts实例
  var myChart = echarts.init(ele);

  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option);
}
function getXX(key) {
  var xxJson = {
    "00": "晴",
    "01": "多云",
    "02": "阴",
    "03": "阵雨",
    "04": "雷阵雨",
    "05": "雷阵雨伴有冰雹",
    "06": "雨夹雪",
    "07": "小雨",
    "08": "中雨",
    "09": "大雨",
    10: "暴雨",
    11: "大暴雨",
    12: "特大暴雨",
    13: "阵雪",
    14: "小雪",
    15: "中雪",
    16: "大雪",
    17: "暴雪",
    18: "雾",
    19: "冻雨",
    20: "沙尘暴",
    21: "小到中雨",
    22: "中到大雨",
    23: "大到暴雨",
    24: "暴雨到大暴雨",
    25: "大暴雨到特大暴雨",
    26: "小到中雪",
    27: "中到大雪",
    28: "大到暴雪",
    29: "浮尘",
    30: "扬沙",
    31: "强沙尘暴",
    32: "浓雾",
    33: "雪",
    49: "强浓雾",
    53: "霾",
    54: "中度霾",
    55: "重度霾",
    56: "严重霾",
    57: "大雾",
    58: "特强浓雾",
    99: "无",
  };
  return xxJson[key];
}
class Image {
  constructor() {
    // __zr.dom
    this.currentSrc = null;
    this.naturalHeight = 0;
    this.naturalWidth = 0;
    this.width = 0;
    this.height = 0;
    this.tagName = "IMG";
  }
  set src(src) {
    console.log(`11323123213:`);
    this.currentSrc = src;
    uni.getImageInfo({
      src,
      success: (res) => {
        this.naturalWidth = this.width = res.width;
        this.naturalHeight = this.height = res.height;
        console.log(`imgimg:`, res);

        this.onload(res);
      },
      fail: () => {
        this.onerror();
        console.log(`onerroronerroronerror:`);
      },
    });
  }
  get src() {
    return this.currentSrc;
  }
}
const getImageInfo = (imgSrc) => {
  return new Promise((resolve, errs) => {
    uni.getImageInfo({
      src: imgSrc,
      success: function (image) {
        resolve(image);
      },
      fail(err) {
        console.log(`err:`, err);
        errs(err);
      },
    });
  });
};

export const drawDayAndNight = async (preTime, sunrise, sunset) => {
  var w = $(".canvas-content").width() * 1;
  var h = $(".canvas-content").height() * 1;
  var center = {
    x: w / 2,
    y: h * 0.82,
  };
  var radius = 0.363 * w;
  //   $("#mycanvas").attr("width", w).attr("height", h);
  //   $("#mycanvas")
  //     .width(w / 2)
  //     .height(h / 2);

  // var t =
  //   data.f0.slice(0, 4) +
  //   "-" +
  //   data.f0.slice(4, 6) +
  //   "-" +
  //   data.f0.slice(6, 8) +
  //   " " +
  //   data.f0.slice(8, 10) +
  //   ":" +
  //   data.f0.slice(10, 12) +
  //   "更新";
  $("#time2").html(preTime);
  // var daynight = data.f1[8]["fi"];
  var start = sunrise; // daynight.split("|")[0];
  var end = sunset; // daynight.split("|")[1];
  // var img = new Image();
  // let imgfile = "";
  // img.src = "https://cdn.kuaidi100.com/images/wxapp/kuaidi100/ico-ji.png";
  //   var img = document.getElementById("imgID");
  // console.log(`IMGI:`, img);
  // let imgfile = await getImageInfo(
  //   "../static/images/forecast/fxfl.png"
  //   // "https://cdn.kuaidi100.com/images/wxapp/kuaidi100/ico-ji.png"
  // );
  // console.log(`res:`, imgfile);

  var t_start = start.split(":")[0] * 60 + parseInt(start.split(":")[1]);
  var t_end = end.split(":")[0] * 60 + parseInt(end.split(":")[1]);
  var t_now = new Date();
  t_now = t_now.getHours() * 60 + parseInt(t_now.getMinutes());
  if (t_now > t_end) {
    t_now = t_end;
  }
  var angle = 0;
  if (t_now > t_start && t_now <= t_end) {
    angle = ((t_now - t_start) / (t_end - t_start)) * Math.PI;
  }

  var requestAnimationFrame =
    window.requestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.msRequestAnimationFrame;
  //   var canvas = document.getElementById("mycanvas");
  var ctx = uni.createCanvasContext("mycanvas");
  console.log(`mycanvasmycanvasmycanvas:`, ctx);

  //   var ctx = canvas.getContext("2d");
  var startAngle = 0;

  function draw() {
    if (startAngle < angle) {
      startAngle = startAngle + 0.1;
      drawAnimate(startAngle);
      requestAnimationFrame(draw);
    } else {
      startAngle = angle;
      drawAnimate(startAngle);
    }
  }
  function drawAnimate(angle) {
    var pointX = center.x - Math.cos(angle) * radius;
    var pointY = center.y - Math.sin(angle) * radius;
    // 区域阴影
    ctx.clearRect(0, 0, w, h);

    ctx.save();
    ctx.beginPath();
    ctx.arc(center.x, center.y, radius, Math.PI, Math.PI + angle, false);
    ctx.lineTo(pointX, center.y);
    ctx.fillStyle = "#fbf5cc";
    ctx.fill();
    ctx.restore();

    // 圆弧间断线
    var density = 60;
    var per = Math.PI / density;
    var own = per * 0.75;
    for (var i = 0; i < density; i++) {
      var startAngle = i * per - Math.PI;
      var endAngle = startAngle + own;

      ctx.save();
      ctx.beginPath();
      ctx.arc(center.x, center.y, radius, startAngle, endAngle, false);
      ctx.lineWidth = 1;
      ctx.strokeStyle = "#ebcf16";
      ctx.stroke();
      ctx.restore();
    }

    // 底部实线
    ctx.save();
    ctx.moveTo(0, center.y);
    ctx.lineTo(w, center.y);
    ctx.lineWidth = 1;
    ctx.strokeStyle = "#e7e7e7";
    ctx.stroke();
    ctx.restore();

    // 两边小圆
    ctx.save();
    ctx.beginPath();
    ctx.arc(center.x - radius, center.y, 0.012 * w, 0, 2 * Math.PI, false);
    ctx.arc(center.x + radius, center.y, 0.012 * w, 0, 2 * Math.PI, false);
    ctx.fillStyle = "#e9cb00";
    ctx.fill();
    ctx.restore();

    // 两边文字
    ctx.save();
    ctx.font = 0.03 * w + "px 微软雅黑";
    ctx.fillStyle = "#868686";
    ctx.textAlign = "center";
    ctx.fillText(start, center.x - radius, center.y + w * 0.05);
    ctx.fillText(end, center.x + radius, center.y + w * 0.05);
    ctx.restore();

    // 绘制晴天符号
    ctx.drawImage(
      indexConfig.baseUrl + "/files/staticFiles/晴-白天.png",
      pointX - 0.045 * w,
      pointY - 0.045 * w,
      0.09 * w,
      0.09 * w
    );
    ctx.draw();
    // ctx.clip();
    // ctx.drawImage(imgfile, 20, 15, 36, 36);
  }
  requestAnimationFrame(draw);
  // return t;
  // ctx.drawImage(
  //   imgfile,
  //   pointX - 0.045 * w,
  //   pointY - 0.045 * w,
  //   0.09 * w,
  //   0.09 * w
  // );
  // requestAnimationFrame(draw);
  // img.onload = function (res) {
  //   // console.log(`res:`, res);
  //   // imgfile = res;
  //   console.log(`res:`, imgfile);
  //   requestAnimationFrame(draw);
  // };
};
function getXXImg(key, keystr) {
  if (keystr.indexOf("到") !== -1) {
    keystr = keystr.split("到")[1];
  }
  var hour = new Date().getHours();
  if (key == 0 || key == 1 || key == 3 || key == 13) {
    if (hour > 8 && hour < 20) {
      return keystr + "-白天";
    } else {
      return keystr + "-夜间";
    }
  }
  return keystr;
}
function getWindDirection(n) {
  var data = "1";
  switch (n) {
    case "0":
      data = "微风";
      break;
    case "1":
      data = "东北风";
      break;
    case "2":
      data = "东风";
      break;
    case "3":
      data = "东南风";
      break;
    case "4":
      data = "南风";
      break;
    case "5":
      data = "西南风";
      break;
    case "6":
      data = "西风";
      break;
    case "7":
      data = "西北风";
      break;
    case "8":
      data = "北风";
      break;
    case "9":
      data = "旋转风";
      break;
    default:
      break;
  }
  return data;
}
function getAqiLevel(aqi) {
  if (aqi < 50) {
    return {
      level: 1,
      info: "优",
    };
  } else if (aqi < 101) {
    return {
      level: 2,
      info: "良",
    };
  } else if (aqi < 151) {
    return {
      level: 3,
      info: "轻度",
    };
  } else if (aqi < 201) {
    return {
      level: 4,
      info: "中度",
    };
  } else if (aqi < 301) {
    return {
      level: 5,
      info: "重度",
    };
  } else {
    return {
      level: 6,
      info: "严重",
    };
  }
}
// 视频H5兼容处理
function initVideo(_video) {
  var ua = navigator.userAgent.toLocaleLowerCase();
  if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null) {
    _video.setAttribute("x-webkit-airplay", true);
    _video.setAttribute("x5-playsinline", true);
    _video.setAttribute("webkit-playsinline", true);
    _video.setAttribute("playsinline", true);
  } else {
    //ios端
    _video.setAttribute("webkit-playsinline", true);
    _video.setAttribute("playsinline", true);
  }
}
// 过去24小时图片集
function addPassImgList(list) {
  var str = "";
  list.forEach((item) => {
    str += `<li>
            <img src="${item.img}" alt="">
        </li>`;
  });
  $(".passimglist").html(str);
}
// 图片集点击查看大图
function initImgsEvent() {
  $(".passimglist li").on("click", function () {
    var index = $(this).index();
    console.log(index);
    swiper.slideTo(index, 0);
    $(".swiper-container").show();
    $("#pastVideo").hide();
  });
}
//补零
function addZero(n) {
  return n >= 10 ? n + "" : "0" + n;
}
//时间函数
function timeObj() {
  var oDate = new Date();
  return {
    year: oDate.getFullYear(),
    month: addZero(oDate.getMonth() + 1),
    date: addZero(oDate.getDate()),
    hours: addZero(oDate.getHours()),
    minutes: addZero(oDate.getMinutes()),
  };
}
// 轮播图图片添加
function addSwiperList(list) {
  var str = "";
  list.forEach(function (item) {
    str += `
        <div class="swiper-slide">
            <div class="swiper-zoom-container">
                <img src="${item.bigImg}">
            </div>
        </div>`;
  });
  $("#swiperWrapper").html(str);
}
// 当前实况
function initPresent(dataObj) {
  var t = dataObj.f.f0;
  t =
    t.slice(0, 4) +
    "-" +
    t.slice(4, 6) +
    "-" +
    t.slice(6, 8) +
    " " +
    t.slice(8, 10) +
    ":" +
    t.slice(10, 12) +
    "更新";
  $(".shikuang .title span").html(t);
  var pm25 = dataObj.k.k1.split("|");
  pm25 = pm25[pm25.length - 1];
  var aqi = dataObj.k.k3.split("|");
  aqi = aqi[aqi.length - 1];
  var temp = dataObj.jh[0]["jb"];
  var warning = dataObj.w;
  if (warning.length) {
    warning = warning[0]["w7"] + warning[0]["w5"] + "预警";
  } else {
    warning = "无";
  }
  if (dataObj) {
    $("#present li:eq(0)").html("温度：" + (temp || "--") + "℃");
    $("#present li:eq(1)").html("清新指数：" + (dataObj.atballtemp || "--"));
    $("#present li:eq(2)").html("负氧离子：" + (dataObj.atballtemp || "--"));
    $("#present li:eq(3)").html("PM2.5：" + (pm25 || "--"));
    $("#present li:eq(4)").html("AQI：" + (aqi || "--"));
    $("#present li:eq(5)").html("预警：" + warning);
  }
}
function initCenterList(dataObj) {
  var str = `<ul class="list${dataObj.arr.length}">`;
  dataObj.arr.forEach(function (item, index) {
    str += ` <li>
                 <div class="title2">
                     <p>${
                       dataObj.img[index]
                         ? '<img src="' + dataObj.img[index] + '" alt="">'
                         : ""
                     }${dataObj.name[index + 1]}</p>
                     <div class="val2">
                     ${item}<b>${dataObj.unit}</b>
                     </div>
                 </div> 
             </li>`;
  });
  str += "</ul>";
  return str;
}

var _url = "";
function loadImage(url) {
  var img = new Image();
  img.addEventListener("load", loadHandler);
  img.src = url;
  _url = url;
}
function loadHandler(e, s) {
  console.info(e, s);
  //$('#id_test_video video').attr('poster', _url);
  $("#id_test_video .vjs-poster").css(
    "background-image",
    'url("' + _url + '")'
  );
  $("#history_video .vjs-poster").css(
    "background-image",
    'url("' + _url + '")'
  );
}

// $(function () {
//   var lon = 118.122171,
//     lat = 25.690288;
//   // 初始化视频
//   // $.getJSON("https://api.bluepi.tianqi.cn/Outdata/other/getNetEyeInfo/id/5107_9d6d507c194311e992905cb9018cf0d4",function(res){

//   var code = "0eeffe9c10514f54bc0cfaff0826b11b";
//   var transcode = 1;
//   var framerate = 0;
//   var resolution = "720P";
//   if (getQueryVariable("code")) {
//     code = getQueryVariable("code");
//   }
//   if (getQueryVariable("transcode")) {
//     transcode = getQueryVariable("transcode");
//   }
//   if (getQueryVariable("framerate")) {
//     framerate = getQueryVariable("framerate");
//   }
//   if (getQueryVariable("resolution")) {
//     resolution = getQueryVariable("resolution");
//   }
//   $.getJSON("/Hik/GetCapture?code=" + code, function (res) {
//     loadImage(res.data.picUrl);
//   });

//   $.getJSON(
//     "/Hik/GetUrl?code=" +
//       code +
//       "&transcode=" +
//       transcode +
//       "&framerate=" +
//       framerate +
//       "&resolution=" +
//       resolution,
//     function (res) {
//       $("#id_test_video source").attr("src", res.data.url);
//       $("#id_test_video").height(($("body").width() * 720.0) / 1280 + "px");
//       $("#id_test_video ").attr("poster", res.data.picUrl);
//       videojs("id_test_video");

//       $("#history_video source").attr(
//         "src",
//         "/history/" + code + ".mp4?r=" + Math.random()
//       );
//       $("#history_video").height(($("body").width() * 720.0) / 1280 + "px");
//       $("#history_video ").attr("poster", res.data.picUrl);
//       $("#history_video_cover").height(
//         ($("body").width() * 720.0) / 1280 - 40 + "px"
//       );

//       videojs("history_video", { replay: true });
//       $("#history_video ").find("video").show();
//     }
//   );
//   $.getJSON(
//     "http://www.qzqxw.com/api/v1/live/minutes/58931/Min?tk=xMGrAdP2VvNJHELk",
//     function (res) {
//       if (res.status !== 200) return;
//       var obj = res.data;
//       $("#time").html(obj.obs_time + "更新");
//       $(".weather-temp").html(obj.tem);
//       $(".detail-humwind").html("相对湿度：" + obj.humidity);
//       $(".detail-air").html(
//         "风向风速：" + obj.two_wind_direction + obj.two_wind_speed
//       );
//       $(".detail-njd").html("能见度：" + obj.visibility);
//       var day_rainfall = parseFloat(obj.day_rainfall);
//       if (day_rainfall > 0) {
//         $(".detail-jyl").html("日雨量：" + day_rainfall + "毫米");
//       } else {
//         $(".detail-jyl").hide();
//       }
//     }
//   );

//   $.getJSON(
//     "http://decision-admin.tianqi.cn/Home/other/getWeather?lon=" +
//       lon +
//       "&lat=" +
//       lat,
//     function (res) {
//       console.log(`res:`, res);
//       drawDayAndNight(res.f);
//     }
//   );

//   // 菜單切換
//   $(".weather-menus li").on("click", function () {
//     var index = $(this).index();
//     $(this).addClass("act").siblings().removeClass("act");
//     $("#box>li").hide();
//     $("#box>li:eq(" + index + ")").show();
//   });
// });

function ctrlHistoryVideo() {
  if ($("#history_video").find("video")[0].paused)
    $("#history_video").find("video")[0].play();
  else $("#history_video").find("video")[0].pause();
}

// var swiper = new Swiper(".swiper-container", {
//   zoom: true,
//   pagination: {
//     el: ".swiper-pagination",
//     type: "fraction",
//   },
//   observer: true,
//   navigation: {
//     nextEl: ".swiper-button-next",
//     prevEl: ".swiper-button-prev",
//   },
//   on: {
//     click: function () {
//       $("#swiperContainer").hide();
//       $("#pastVideo").show();
//     },
//   },
// });

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return false;
}
